from requests import put, get
from json import loads
from time import sleep
import schedule
from webbrowser import open
from windows_toasts import Toast, WindowsToaster, ToastImage, ToastDisplayImage
from tkinter import simpledialog
import sys
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QAction
from PyQt5.QtGui import QIcon
from threading import Thread
import os

# 设为已读
URL_SET_READ = 'https://api.gitee.com/enterprises/2186826/notifications/mark_read'
# 获取最新通知的列表
URL_LAST_LIST = 'https://api.gitee.com/enterprises/2186826/notifications/source'
# 通知中心页面
NOTICE_WEB = 'https://e.gitee.com/richfun_saas/notifications/infos'
# 请求git通知总数的地址
URL_NOTICE = 'https://api.gitee.com/enterprises/2186826/notifications/unread_count'
# 授权的cookie
# COOKIE = "Hm_lvt_2209fa7fc7287fd766adbc9f6d451b8f=1690855922; Hm_lvt_c3e4c659b69bd9cf4eca2be9aa416c0c=1692321529; Hm_lvt_5ce3573d3237b56a4e39ae791cd3ff9e=1692604801,1695113732; sensorsdata2015jssdkchannel=%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D; Hm_lvt_dbba4dc235af9a121ecb9ae949529239=1697533488; Hm_lvt_0714711a5733da29a7a14d31b8524210=1698982287; Hm_lvt_0a08804d2a2e6f0d7e02dd4ed95b5f5c=1699254704; remember_user_token=BAhbCFsGaQNqaBdJIiIkMmEkMTAkaHplVmw2N1hJajhsdHgyV3NFY0xzZQY6BkVUSSIXMTcwMTMyNDE2NC4xOTgzMDQyBjsARg%3D%3D--1bfaedce24ecac9dcda250e17a903eef28a67d04; user_locale=zh-CN; Hm_lvt_925c8ee26036ae378c90125c50e88939=1701927477; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%221534058%22%2C%22first_id%22%3A%2218c1ed27e74719-0994f271eb120d-26031051-2073600-18c1ed27e751835%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_utm_source%22%3A%22alading%22%2C%22%24latest_utm_medium%22%3A%22sem%22%2C%22%24latest_utm_campaign%22%3A%22repo%22%2C%22%24latest_utm_content%22%3A%22competition%22%2C%22%24latest_utm_term%22%3A%22git%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTg5NzIwZGE1MWQxOGMtMGExODVlZjQ4ZDRmMjctMjYwMzFjNTEtMjA3MzYwMC0xODk3MjBkYTUxZTEzNWUiLCIkaWRlbnRpdHlfbG9naW5faWQiOiIxNTM0MDU4In0%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%221534058%22%7D%2C%22%24device_id%22%3A%22189720da51d18c-0a185ef48d4f27-26031c51-2073600-189720da51e135e%22%7D; Hm_lvt_24f17767262929947cc3631f99bfd274=1701324158,1701658397,1701944539,1702260981; BEC=1f1759df3ccd099821dcf0da6feb0357; Hm_lvt_6e50b86c88f8d4c42ecff4d401c9b58b=1702361043; Hm_lpvt_6e50b86c88f8d4c42ecff4d401c9b58b=1702361043; go_canary=richfun_saas; csrf_token=teYSylZUFBfMjx%2FODIInxDlLJxN51lRLZTIxbPEDjlIEtpbgC%2BljKcI3PhSD0Z%2Bs%2FgwLZvVSXbZztszmq7AB%2FA%3D%3D; Hm_lpvt_24f17767262929947cc3631f99bfd274=1702369709; gitee-session-n=RFZnY0hDNzBibVE3bGswd3oxVTRDNlRVQk14MkxwWFI3akZWVHJtS2pUUDNWMXkvRWNYOTFCTUFQWUY5aUdrT0MzQ0ltNEZ3L0IzeWUxWGg4Nm5lNmVSOG5GNWpla1oyMlZEKzBsR3dOM3JhaWdRRzhFb1pocG93YWhnVE9Hd2tRVTJjUXlWalYvMncvUVpVQVJMNkcrdjZEU1Q5K2F3WTJPSHYxU1VNaDQrOE96Q2VPWXdVb09wMzZrMDV2dCtKZXN6cEFpekR0emxJZEkxU29lOGc1S29ubXdSSkhsbnBqVEt2ZHZCcmRzalM3SExYR3J5WEQ2M0lrSXpieklaUkQ0bWpYUlNtRmlONWU1ZXNJMTh2VC9vT3BiWmZtcFdIdGt6MTUrVHR2c0VYSDhJb3E4SVowd3NOczFGZ3JEaVZkZEh0UUJFazVxcGFQYzZWMGFONUJMNUkva29mTitVWFE1R0JOcTdPWG5rUkVkSzQwZUxCWkdySE5DcU9JcTFiMVlEM1JaMVpwdjlWTS9qOUhGNlZ3L2lxRWNyTlN2M0ZSelF3VXRqN0IzTHNSOCt5QThucXl0UE1EcmZaaTU2eGtmOXNNaXAxQ3NPbWEvRHN3a2tNMVdjV1dmdmc1b01pZG8vM1J0eU9TVVJFU043KzA2M2RaL1FrWGdlSmVPUlBFTXI2SWl4Qmd2VytQcE1tVk5HUzhHNTFLYk1Nb0dkZkh0alZWQ1ZmTHpuY2d6Z1N5RGI4NmdIejAxRDJiTzE0Mmp3R2lXZTNldUFqakpQU1Jwc2RFZ0NTWUxPaGtoeTU3MUFGOTVtUlVuTT0tLXl1eldrSGpiK0ZyM3lNSXlOUks0YlE9PQ%3D%3D--3380cec1710408e2172e836c60aa9be1120892de"
COOKIE = ''
# 通知图标
NOTICE_ICON = r'E:\project\practice\notice\resource\git.ico'
# 每隔多久请求一次 单位秒
INTERVAL = 180

CONTINE = True
headers = {
  "cookie": COOKIE,
  "host": "api.gitee.com"
}

app = QApplication(sys.argv)

'''
打开任务详情
'''


def open_process_detail(url=None):
  if url is not None:
    open(url=url, new=0)


'''
设置通知消息已读
'''


def mark_read(ids=None):
  if ids is None:
    ids = []
  data = {
    "ids": ids,
    "type": "event"
  }

  put(URL_SET_READ, headers=headers, data=data)


'''
获取最新的通知
'''


def query_last_list(total=3):
  param = {
    "page": 1,  # 页码
    "type": "event",  # 通知类型
    "per_page": total,  # 总数
    # "scope": "participant"  # 通知范围， participant：只看与自己相关的
  }

  content = get(URL_LAST_LIST, params=param, headers=headers).text
  return loads(content)['data']


'''
设置cookie
'''


def set_cookie(v):
  COOKIE = v


def init_cookie():
  cookie = headers['cookie']
  CONTINE = False
  user_input = simpledialog.askstring("git cookie", "请输入可用cookie：",
                                      initialvalue=cookie)
  COOKIE = user_input
  headers['cookie'] = user_input
  CONTINE = True


'''
查询是否存在新的通知
:res:返回新通知的个数
'''


def has_new_notice():
  content = get(URL_NOTICE, headers=headers)
  if content.status_code.__eq__(411):
    # 登录过期，弹窗请求获取最新的cookie
    init_cookie()
    return -1
  text = content.text
  total = loads(text)["event"]
  # 从请求返回头中获取cookie
  new_cookie = content.headers.get("Set-Cookie")
  set_cookie(new_cookie)
  return total


def job():
  print("开始检测是否存在新的通知")
  # 先判断是否存在未读消息
  total = has_new_notice()

  if total > 0:
    # 查询出一条数据并展示
    list = query_last_list(1)

    # 调用系统通知弹窗提示新的变更
    item = list[0]
    print(f"检测到新的动态：{item['content']}")
    toaster = WindowsToaster('git消息推送')
    newToast = Toast()
    ic = ToastImage(NOTICE_ICON)
    imgs = ToastDisplayImage(ic)
    newToast.AddImage(imgs)
    newToast.text_fields = [item['content']]
    # 状态为 type='issue_assign' 蔡添加打开网页的动作
    type = item['type']
    path = ''
    if type == 'issue_assign' or type == 'issue_state_change':
      # 跳转到工作台并展开该条issue
      path = f'https://e.gitee.com{item['namespace']['path']}/dashboard?issue={item['target']['ident']}'
    # 项目提交则跳转到具体的提交页面
    if type == 'project_push':
      path = f'{item['html_url']}'
    print(path)
    newToast.on_activated = lambda a: open_process_detail(path)
    toaster.show_toast(newToast)

    # 通知之后将该条消息设置为已读
    mark_read(item['id'])
  print("检测完成")


def get_resource_path(relative_path):
  if getattr(sys, 'frozen', False):
    base_path = sys._MEIPASS
  else:
    base_path = os.path.abspath('.')
  return os.path.join(base_path, relative_path)


'''
获取执行授权
'''


def start():
  app.setApplicationName("git通知助手")
  app.setWindowIcon(QIcon(NOTICE_ICON))
  # 创建系统托盘对象
  path = get_resource_path(os.path.join("resource", 'git.ico'))
  tray_icon = QSystemTrayIcon(QIcon(path), app)
  tray_icon.show()

  # 创建右键菜单
  menu = QMenu()
  setAction = QAction("设置会话cookie", triggered=init_cookie)
  quitAction = QAction("退出", triggered=exist)
  enterWebAction = QAction("进入gitee通知中心", triggered=ente_web)
  menu.addAction(setAction)
  menu.addAction(quitAction)
  menu.addAction(enterWebAction)
  menu.addSeparator()
  menu.addAction(quitAction)
  tray_icon.setContextMenu(menu)
  # 启动新线程
  # 初始化工作
  init_cookie()
  ap = Thread(target=run)
  ap.daemon = True
  ap.start()
  sys.exit(app.exec_())


def ente_web():
  open(url=NOTICE_WEB, new=0)


'''
退出系统
'''


def exist():
  sys.exit(app.exit())


def run():
  schedule.every(INTERVAL).seconds.do(job)

  while True:
    if CONTINE is not True:
      break
    schedule.run_pending()

    sleep(1)


'''
定时获取通知消息并提示
'''

if __name__ == '__main__':
  start()


